# 此接口用于删除orthanc上所有的重复模态，保留最新的那个模态
#还没写完

from pyorthanc import find, Orthanc
orthanc = Orthanc('http://localhost:8042',
                  username='orthanc', password='orthanc')

from application import db

import os

class Study_id(db.Model):
    __tablename__ = 'study_id'

    id = db.Column(db.Integer, primary_key=True)
    study_id = db.Column(db.String(255, 'utf8_general_ci'), unique=True,info='dicom study instance uid')
    orthanc_id = db.Column(db.String(255, 'utf8_general_ci'), info='orthanc study id')

    def __init__(self,study_id,orthanc_id):
        self.study_id = study_id
        self.orthanc_id = orthanc_id


def delete_err_series(series_info):
    series_name = series_info['series_name']
    ort_ser_id = series_info['series_id']

    if  't2' not in series_name and 't1' not in series_name and 'ADC' not in series_name and 'tra_dark-fluid' not in series_name:
        delete_based_id(ort_ser_id)

    elif 'PosDisp' in series_name or 'daohang' in series_name or 'cor' in series_name or 'axi' in series_name or 'sag' in series_name or 'hemo' in series_name:
        delete_based_id(ort_ser_id)


def delete_series(ort_study_id):
    # 删除当前study的重复序列
    patients = find(
          orthanc=orthanc,
          study_filter=lambda s: s.id_ == ort_study_id
      )
    # 记录所有series name,series time和seriesid,组成一个字典series_dict
    # series_dict={
    # "1":{series_id:XXX,series_name:XXX,series_time:XXX}
    # "2":{series_id:XXX,series_name:XXX,series_name:XXX}
    # "3":{series_id:XXX,series_name:XXX,series_time:XXX}
    # }
    # 遍历所有序列，如果出现重复/类似的名字，则比对其对应的series time,删掉series time小的series  
    series_dict={}
    i=0
    for patient in patients:
      for study in patient.studies:
        if study.id_ == ort_study_id:
          for series in study.series:
              i+=1
              series_info=series.get_main_information()
              series_dict[i]={'series_id': series_info['ID'],'series_name': series_info['MainDicomTags']['SeriesDescription'],'series_time':series_info['MainDicomTags']['SeriesTime']}
              delete_err_series(series_dict[i])
          break
    # print(series_dict)
    if i>3:
      flag_t1={}
      flag_t2={}
      flag_ADC={}
      for j in range(1,i+1):
        if 't2' in series_dict[j]['series_name']:
            flag_t2[j]=series_dict[j]
        elif 't1' in series_dict[j]['series_name']:
            flag_t1[j]=series_dict[j]
        elif "ADC" in series_dict[j]['series_name']:
            flag_ADC[j]=series_dict[j]
      
      if len(flag_t1)>1:
        # 再重新组装一个字典 用来比较大小
        t1_dict={}
        for item in flag_t1.values():
           d={item['series_id']:item['series_time']}
           t1_dict.update(d)
        # print(t1_dict)
        min_id=min(t1_dict.keys(),key=(lambda x:t1_dict[x]))
        # print(min_id)
        # print(t1_dict[min_id])
        delete_based_id(min_id)
        
      if len(flag_t2)>1:
        t2_dict={}
        for item in flag_t2.values():
           d={item['series_id']:item['series_time']}
           t2_dict.update(d)
        # print(t2_dict)
        min_id=min(t2_dict.keys(),key=(lambda x:t2_dict[x]))
        # print(min_id)
        # print(t2_dict[min_id])
        delete_based_id(min_id)
        
      if len(flag_ADC)>1:
        ADC_dict={}
        for item in flag_ADC.values():
           d={item['series_id']:item['series_time']}
           ADC_dict.update(d)
        # print(ADC_dict)
        min_id=min(ADC_dict.keys(),key=(lambda x:ADC_dict[x]))
        # print(min_id)
        # print(ADC_dict[min_id])
        delete_based_id(min_id)     
     
def delete_based_id(ort_ser_id):
    order="curl -X DELETE http://localhost:8042/series/"+ort_ser_id
    os.system(order)


if __name__ == '__main__':   
    # 获取study_id表里面的所有orthanc_id
    
    query = db.session.query(Study_id.orthanc_id).all()
    for item in query:
       orthanc_id=item[0]
       try:
          delete_series(orthanc_id)
       except:
          print("这个删不了{item[0]}")



